var loader;
var bodyVar;

/**
 * start loader
 */
function start(){
	loader.show();
	log("show loader");
}


/**
 * stop loader
 */
function end(){
	log("hide loader");
	loader.hide();
}

function setHeight(id,percentage){
	$("#"+id).css("height",$(window).height()/100*percentage);
};

function setWidth(id,percentage){
	$("#"+id).css("width",$(window).width()/100*percentage);
};

function log(mes){
	if($.browser.msie){
		alert(mes);
	}else{
		console.log(mes);
	}
}

function setFormOk(form){
	log("setFormOK");
	var submit=$("input[type='submit']",form);
	var loader=$("<div/>");
	loader.attr("id","ldr");
	loader.append("Salvataggio in corso");
	submit.hide();
	submit.parent().append(loader);
	//setTimeout(function(){loader.remove();submit.show();},1500);
}

function rmFormOk(form){
	log("rmFormOK");
	var submit=$("input[type='submit']",form);
	var loader=$("#ldr",submit.parent());
	loader.remove();
	submit.show();
}

function ajaxPost(args,form,formType){
	
	var loc=window.location.pathname;
	loc=loc.replace("/sparkle", "");
	
	start();
	
	$.ajax({
		url: '/sparkle/portal/actions',
		cache: false,
		type: "POST",
		data: args,
		dataType: "json",
		async: false,
		success: function(result) {
			//onSuccess(result);
			/*
			if(form && form.hasClass("showsave"))
				setFormOk(form);
				*/
			parseResult(result);
			/*
			if(form && form.hasClass("showsave"))
				rmFormOk(form);
				*/
			end();
		},
		error: function(error){
			//parseResult(error);
			alert("Unable to comunicate with server");
			end();
		}
	});
	
};

function postAjaxForm(id,validate){
	var form=$("#"+id);	
	if(validate){
		var ok=validateForm(form);
		log("form validation result:"+ok);
		if(ok)
			ajaxPost(form.serialize(),form);
	}else{
		ajaxPost(form.serialize(),form);
	}
}

function validateForm(form){
	var ret=true;
	$("input",form).each(function(){
		validateClean($(this));
		if($(this).is(".required") && $.trim($(this).val()).length==0){
			$(this).parents(".control-group").addClass("error");
			if(ret)
				ret=false;
		}else{
			$(this).addClass("input-success");
		}
	});
	return ret;
}

function validateClean(input){
	input.parents(".control-group").removeClass("success");
	input.parents(".control-group").removeClass("error");
	input.parents(".controls").find(".help-inline").remove();
	input.removeClass("input-error");
};

function onClick(id){
	id="listenerid="+id;
	ajaxPost(id);
}

function parseResult(result){
	
	//json
	$.each(result,function(index, value) { 
		  log(index + ': ' + value.id);
		  
		  if(value.id=='jqscript'){
			  var scr="<script>";
			  $.each(value.states,function(index2,value2){
				  log(value2.value);
				  scr+=value2.value;
			  });
			  scr+="</script>";
			  log(scr);
			  $("body").append(scr);
		  }else{
			  $.each(value.states,function(index2,value2){
				 parseElementResult(value.id,value.states);
			  });
		  }
	});	
}

function parseElementResult(id,states){
	//find element
	var el=null;
	if(id == 'window')
		el=$(window);
	if(id=='document')
		el=$(window);
	if(!el){
		if(id.substring(0,1)==='#' || id.substring(0,1)==='.'){
			el=$(id);
		}else{
			el=$('#'+id);
		}
	}
	
	if(!el || el.length==0){
		log("Errore: no element found");
		return;
	}
	
	$.each(states,function(index, value) { 		
		applyResult(id,el,value.name,value.value);
	});	
}

//Array possible actions
var functions=new Array();
functions["text"]="el.text('@var');";
functions["open"]="el.modal('show');";
functions["close"]="el.modal('hide');";
functions["addclass"]="el.addClass('@var');";
functions["rmclass"]="el.removeClass('@var');";
functions["addclassBySelector"]="el.addClass('@var');";
functions["rmclassBySelector"]="el.removeClass('@var');";
functions["hide"]="el.hide()";
functions["show"]="el.show()";
functions["showTemp"]="el.show(); setTimeout(function(){el.hide()},@var);";
functions["replace"]="el.parent().html('@var')";
functions["append"]="el.append('@var')";
functions["html"]="el.html('@var')";
functions["removeclick"]="$(document).off('click','@var')";
functions["disable"]="el.attr('disabled','disabled')";
functions["enable"]="el.removeAttr('disabled')";
functions["redirect"]="el.attr('location','@var')";
functions["openUpload"]="openUpload(el)";
functions["startUpload"]="startUpload('@var')";
functions["trigger"]="el.trigger('@var')";
functions["textEditor"]="aceEditor.setValue('@var')";

function applyResult(id,el,name,value){
	//var el=element;	
	
	func=functions[name];
	if(!func){
		log("Function "+name+" is not defined");
		return;
	}
	func=func.replace("@var",value);
	log(func);
	eval(func);
}

/*
 * Carico la prima pagina all'avvio
 */
$(document).ready(function(){
	
	loader=$("#loading");
	bodyVar=$("body");

	start();
	
	var loc=location.href;
	
	//alert(loc);
	
	$.ajax({
		url: loc+'/index',
		cache: false,
		type: "GET",
		//data: args,
		dataType: "html",
		async: false,
		success: function(result) {
			$("#page-container").html(result);
			end();
		},
		error: function(error){
			alert("Unable to comunicate with server");
			end();
		}
	});
	
	$(document).on("submit","form",function(e){
		//$(this).
		e.preventDefault();
		alert("Default submit");
	});
	
});



function openUpload(iFrameDiv){
	var getAddFile=iFrameDiv.attr("get-add-file");
	var iFrameDivClone=iFrameDiv.parent().clone();
	
	var table=iFrameDiv.parents("table");
	
	log(iFrameDivClone);
	log(table);
	
	var iframeP=null,iframe=null;
	iFrameDiv.find('iframe').each(function(){
		if($(this).attr("class")=='submit')
			iframe=$(this);
		if($(this).attr("class")=='progress')
			iframeP=$(this);
	});
	
	
	var ifile=iframe.contents().find('input[type="file"]');
	var prBtn=iframeP.contents().find('input[type="button"]');
	var addFileLink=$("a[iframe='"+iFrameDiv.attr("id")+"']");
	
	ifile.bind($.browser.msie ? "propertychange" : "change",function(){
		log("On fileupload change");
		var fileName=$(this).val().replace("C:\\fakepath\\","");
		var progressId=prBtn.attr("pid");
		addFileLink.replaceWith("<div class='progress progress-striped active'><div id="+progressId+" class='bar' style='width: 0%;'></div></div><div class='span2'>"+fileName+"</div>");		
		if(getAddFile)
			ajaxPost("listenerid="+getAddFile);
	});
	
	ifile.trigger("click");
}

window.updateProgress=function(selector,read,content){
	log("progress selector:"+selector);
	$(selector).css('width',parseInt((read*100/content), 10)+'%');
};


function startUpload(tid){
	if($("#"+tid+" td").size()==1)
		return
	var td=$("#"+tid+" td").first();	
	if(td){
		var iframeP=null,iframe=null;
		td.find('iframe').each(function(){
			if($(this).attr("class")=='submit')
				iframe=$(this);
			if($(this).attr("class")=='progress')
				iframeP=$(this);
		});
		
		
		var submitBtn=iframe.contents().find('form');
		var prBtn=iframeP.contents().find('input[type="button"]');
			
		iframe.load(function(responseText, textStatus, XMLHttpRequest){
			
			log("on iframe load");
				
			if($.browser.msie){
				var jsonResponse = iframe.contents().find("textarea").text();
				//alert(jsonResponse);
				parseResult(eval(jsonResponse));
			}else{
				parseResult(eval(iframe.contents().find("pre").text()));
			}			
			td.remove();
			startUpload(tid);
		});
		submitBtn.submit();
		prBtn.trigger("click");
	}
}



